//
//  DTWebViewController.m
//  hnGovernment
//
//  Created by zhn on 2017/3/13.
//  Copyright © 2017年 安仔. All rights reserved.
//

#import "DTWebViewController.h"
#import "WebViewJavascriptBridge.h"
#import "DDFilteredProtocol.h"
#import "DTJavascriptCommand.h"
#define KOAuthBaseURL @"http://42.236.64.63:8081/uaa/authorize"
@interface DTWebViewController ()<UIWebViewDelegate,UIGestureRecognizerDelegate>
@property (nonatomic,strong) WebViewJavascriptBridge *bridge;
@property (nonatomic,strong) DTJavascriptCallManager *nativeCallManager;
@property (nonatomic,assign) BOOL isOAuthing;
@property (nonatomic,strong) UIButton *closeButton;
@property (nonatomic,strong) UIActivityIndicatorView *indicatorView;
@end

@implementation DTWebViewController
#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.webView];
    [self p_setupBackButton];
    [self p_setUpWebViewBridge];
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.webViewUrlString]]];
    [NSURLProtocol registerClass:[DDFilteredProtocol class]];
    [self.view addSubview:self.indicatorView];
    [self.indicatorView startAnimating];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)dealloc {
    self.webView.delegate = nil;
    [self.webView stopLoading];
    [NSURLProtocol unregisterClass:[DDFilteredProtocol class]];
}
#pragma mark - public methods
-(void) initRefresh {
    [self.webView addGestureRecognizer:_recognizer];
}


#pragma mark - target action
- (void)webViewGobackAction {
    if ([self.webView canGoBack]) {
        [self.webView goBack];
        self.closeButton.hidden = NO;
    }else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)popViewControllerAction {
    [self.navigationController popViewControllerAnimated:YES];
}

-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return true;
}

- (void)handleSwipeFrom:(UISwipeGestureRecognizer*)recognizer {
    // 触发手勢事件后，在这里作些事情
    //    [self.uiWebView reload];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //[self loadExamplePage];
        NSLog(@"11111%@",[NSThread currentThread]);
    });
    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"22222%@",[NSThread currentThread]);
        
    });
}
#pragma mark - delegates
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    
    NSString *targetURL = request.URL.absoluteString;
    NSLog(@"%@",targetURL);
    if (self.webView) {
        if (self.isOAuthing) {return YES;}
        if ([targetURL hasPrefix:KOAuthBaseURL]) {
            NSMutableURLRequest *mutableRequest = [request mutableCopy];
            NSString *url = mutableRequest.URL.absoluteString;
            mutableRequest.URL = [NSURL URLWithString:[NSString stringWithFormat:@"%@&refresh_token=%@", url, @"jDWb014QSIsAAAAAAAArMY7GKJySXct0"]];
            [mutableRequest addValue:@"jDWb014QSIsAAAAAAAArMY7GKJySXct0" forHTTPHeaderField:@"refresh_token"];
            [self.webView loadRequest:mutableRequest];
            self.isOAuthing = YES;
            return NO;
        }
    }
    return YES;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    [self.indicatorView stopAnimating];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    [self.indicatorView stopAnimating];
    [SVProgressHUD showErrorWithStatus:@"链接错误,加载失败"];
}

#pragma mark - pravite methods
- (void)p_setUpWebViewBridge {
    if (self.bridge) {return;}
    [WebViewJavascriptBridge enableLogging];
    self.bridge = [WebViewJavascriptBridge bridgeForWebView:self.webView];
    [self.bridge setWebViewDelegate:self];
    
    [_bridge registerHandler:@"testObjcCallback" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"testObjcCallback called: %@", data);
        responseCallback(@"Response from testObjcCallback");
    }];
    [_bridge registerHandler:@"dd.native.call" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"dd.native.call called: %@",data);
        responseCallback(@"Response from dd.native.call");
        NSDictionary *dic = data;
        if (dic) {
            NSLog(@"dd.native.call1111:%@", dic);
            DTJavascriptCommand *command = [[DTJavascriptCommand alloc]init:[NSString stringWithFormat:@"%@",dic[@"handlerName"]] anddata:dic[@"params"] andresponscallback:responseCallback andwebView:nil andcontroller:self];
            [self.nativeCallManager exectue: command];
        }else {
            responseCallback(@"invilide data call.");
        }
    }];
    [_bridge callHandler:@"testJavascriptHandler" data:@{ @"foo":@"before ready" }];
}

- (void)p_setupBackButton {
    UIView *webViewMenuView = [[UIView alloc]init];
    webViewMenuView.frame = CGRectMake(0, 0, 120, 80);
    UIButton *popVCbutton = [[UIButton alloc]init];
    [popVCbutton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [popVCbutton setTitle:@"返回" forState:UIControlStateNormal];
    [popVCbutton addTarget:self action:@selector(webViewGobackAction) forControlEvents:UIControlEventTouchUpInside];
    [webViewMenuView addSubview:popVCbutton];
    popVCbutton.frame = CGRectMake(0, 0, 60, 80);
    [popVCbutton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [popVCbutton setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [popVCbutton setTitleEdgeInsets:UIEdgeInsetsMake(0, 10, 0, 0)];
    [popVCbutton setImageEdgeInsets:UIEdgeInsetsMake(0, -10, 0, 0)];
    popVCbutton.imageView.contentMode = UIViewContentModeScaleAspectFill;
    
    UIButton *closeButton = [[UIButton alloc]init];
    closeButton.hidden = YES;
    [closeButton setTitle:@"关闭" forState:UIControlStateNormal];
    [closeButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    closeButton.frame = CGRectMake(50, 0, 80, 80);
    [closeButton addTarget:self action:@selector(popViewControllerAction) forControlEvents:UIControlEventTouchUpInside];
    [closeButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [webViewMenuView addSubview:closeButton];
    self.closeButton = closeButton;
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:webViewMenuView];
}
#pragma mark - setters

#pragma mark - getters
- (DTJavascriptCallManager *)nativeCallManager {
    if (_nativeCallManager == nil) {
        _nativeCallManager = [[DTJavascriptCallManager alloc]init];
    }
    return _nativeCallManager;
}

- (UIWebView *)webView {
    if (_webView == nil) {
        _webView = [[UIWebView alloc]initWithFrame:self.view.bounds];
        _webView.delegate = self;
    }
    return _webView;
}

- (UISwipeGestureRecognizer *)recognizer {
    if (_recognizer == nil) {
        _recognizer = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(handleSwipeFrom:)];
        _recognizer.direction = UISwipeGestureRecognizerDirectionDown;
        _recognizer.delegate = self;
        _recognizer.cancelsTouchesInView = false;
    }
    return _recognizer;
}

- (UIActivityIndicatorView *)indicatorView {
    if (_indicatorView == nil) {
        _indicatorView = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        _indicatorView.hidesWhenStopped = YES;
        _indicatorView.center = CGPointMake(KScreenWidth/2, KScreenHeight/2 - 64);
    }
    return _indicatorView;
}

@end
